package elasticsearch

import (
	"context"
	"easyShop/core/database/elasticsearch"
	"easyShop/model"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"reflect"
	"strconv"
)

var index = "user"

func GetUserCountByUsername(username string) (int, error) {
	conn, _ := elasticsearch.GetConnect()
	// 组建查询器
	search := elastic.NewBoolQuery()
	search.Filter(elastic.NewMatchQuery("username", username))
	// 查询es
	result, err := conn.Search().
		Index(index).
		Query(search).
		Pretty(true).
		Do(context.Background())

	if err != nil {
		return 0, err
	}

	// 获取查询结果总数
	queryCount := result.Hits.TotalHits.Value

	return int(queryCount), nil
}

func GetUserInfoByUsername(username string) (model.User, error, int64) {
	var userInfo model.User
	conn, _ := elasticsearch.GetConnect()
	// 查询es
	result, err := conn.Search().
		Index(index).
		Query(elastic.NewTermQuery("username", username)).
		From(0).
		Size(1).
		Do(context.Background())

	if err != nil {
		return userInfo, err, 0
	}

	if result.Hits.TotalHits.Value == 0 {
		return userInfo, nil, result.Hits.TotalHits.Value
	}

	for _, e := range result.Each(reflect.TypeOf(&model.User{})) {
		us := e.(*model.User)
		userInfo = *us
	}

	return userInfo, nil, result.Hits.TotalHits.Value
}

func GetUserInfoByOpenid(openId string) (model.User, error, int64) {
	var userInfo model.User
	conn, _ := elasticsearch.GetConnect()
	// 查询es
	result, err := conn.Search().
		Index(index).
		Query(elastic.NewTermQuery("openid", openId)).
		From(0).
		Size(1).
		Do(context.Background())

	if err != nil {
		return userInfo, err, 0
	}

	if result.Hits.TotalHits.Value == 0 {
		return userInfo, nil, result.Hits.TotalHits.Value
	}

	for _, e := range result.Each(reflect.TypeOf(&model.User{})) {
		us := e.(*model.User)
		userInfo = *us
	}

	return userInfo, nil, result.Hits.TotalHits.Value
}

func SetUserInfoToEs(userInfo model.User) bool {
	userInfoByte, enJsonErr := json.Marshal(userInfo)
	if enJsonErr != nil {
		return false
	}
	conn, _ := elasticsearch.GetConnect()
	bulk := conn.Bulk()
	request := elastic.NewBulkIndexRequest().
		Index(index).
		Id(strconv.FormatInt(userInfo.Id, 10)).
		Type("_doc").
		Doc(string(userInfoByte))
	_, err := bulk.Add(request).Do(context.Background())
	if err != nil {
		return false
	}

	return true
}
